"use client";

import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
  FrownOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  SettingOutlined,
  SmileOutlined,
} from "@ant-design/icons";
import {
  Button,
  Layout as AntdLayout,
  Menu,
  theme,
  MenuProps,
  Popover,
} from "antd";
import { routes } from "../router";
import { usePathname, useRouter } from "next/navigation";
import { useStore } from "react-redux";
import { RootState } from "../redux/store";
import { RouterItem } from "../redux/reducer";
import { changeIcon } from "../utils/changeMenuicon";
import { ItemType, MenuItemType } from "antd/es/menu/interface";

const { Header, Sider, Content } = AntdLayout;

const getLevelKeys = (items1: RouterItem[]) => {
  const key: Record<string, number> = {};
  const func = (item2: RouterItem[], level = 1) => {
    item2.forEach((item) => {
      if (item.key) {
        key[item.key] = level;
      }
      if (item.children) {
        func(item.children, level + 1);
      }
    });
  };
  func(items1);
  return key;
};

export default function Layout({ children }: { children: React.ReactNode }) {
  const [routerList, setRouterList] = useState<RouterItem[]>(routes);
  const [stateOpenKeys, setStateOpenKeys] = useState<string[]>([]);
  const [levelKeys, setLevelKeys] = useState<Record<string, number>>({});
  const [open, setOpen] = useState(false);

  const store = useStore().getState() as RootState;
  const roleList = store.routesList.router;

  const localStorageRole = useMemo(() => {
    try {
      const data = localStorage.getItem("role");
      if (data) {
        const parsed = JSON.parse(data);
        return parsed?.router || [];
      }
      return [];
    } catch (error) {
      console.error("Failed to parse localStorage role", error);
      return [];
    }
  }, []);

  const getRouterList = useCallback((list: RouterItem[]) => {
    if (!list?.length) return;

    setRouterList((prev) => {
      const filtered = prev.filter(
        (item) => !list.some((role) => role.key === item.key)
      );
      const r_list = [...filtered, ...list];
      setLevelKeys(getLevelKeys(r_list));
      return r_list;
    });
  }, []);

  useEffect(() => {
    if (roleList?.length) {
      getRouterList(roleList);
    } else if (localStorageRole.length) {
      getRouterList(localStorageRole);
    }
  }, [roleList, localStorageRole, getRouterList]);

  const pathname = usePathname();
  const [collapsed, setCollapsed] = useState(false);
  const router = useRouter();

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  const convertToMenuItems = useCallback(
    (items: RouterItem[]): unknown[] => {
      return items.map((item) => {
        if (item.children && item.children.length > 0) {
          return {
            key: item.key,
            icon: changeIcon(item.key || ""),
            label: item.label,
            children: convertToMenuItems(item.children),
          };
        }
        return {
          key: item.key,
          label: item.label,
          icon: changeIcon(item.key || ""),
          onClick: () => {
            if (item.key.lastIndexOf("/") <= 4) {
              setStateOpenKeys([item.key]);
            }
            router.push(item.key as string);
          },
        };
      });
    },
    [router]
  );


  const handleOpenChange = (newOpen: boolean) => {
    setOpen(newOpen);
  };

  const onOpenChange: MenuProps["onOpenChange"] = useCallback(
    (openKeys: string[]) => {
      const currentOpenKey = openKeys.find(
        (key) => stateOpenKeys.indexOf(key) === -1
      );
      // open
      if (currentOpenKey !== undefined) {
        const repeatIndex = openKeys
          .filter((key) => key !== currentOpenKey)
          .findIndex((key) => levelKeys[key] === levelKeys[currentOpenKey]);

        setStateOpenKeys(
          openKeys
            // remove repeat key
            .filter((_, index) => index !== repeatIndex)
            // remove current level all child
            .filter((key) => levelKeys[key] <= levelKeys[currentOpenKey])
        );
      } else {
        // close
        setStateOpenKeys(openKeys);
      }
    },
    [levelKeys, stateOpenKeys]
  );

  return (
    <AntdLayout className="w-full h-full">
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="demo-logo-vertical" />
        <Menu
          theme="light"
          mode="inline"
          defaultSelectedKeys={[pathname]}
          items={convertToMenuItems(routerList) as ItemType<MenuItemType>[]}
          openKeys={stateOpenKeys}
          onOpenChange={onOpenChange}
        />
      </Sider>
      <AntdLayout>
        <Header style={{ padding: 0, background: colorBgContainer }}>
          <div className="flex justify-between items-center px-4">
            <div>
              <Button
                type="text"
                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                onClick={() => setCollapsed(!collapsed)}
                style={{
                  fontSize: "16px",
                  width: 64,
                  height: 64,
                }}
              />
            </div>
            <div className="cursor-pointer">
            <SmileOutlined />
            <FrownOutlined />
              <Popover
                content={<div></div>}
                title="系统设置"
                trigger="click"
                open={open}
                onOpenChange={handleOpenChange}
              >
                <SettingOutlined />
              </Popover>
            </div>
          </div>
        </Header>
        <Content
          style={{
            margin: "24px 16px",
            padding: 24,
            minHeight: 280,
            borderRadius: borderRadiusLG,
          }}
        >
          {children}
        </Content>
      </AntdLayout>
    </AntdLayout>
  );
}
